/**
 * 返回文件扩展名
 * @param {Object} path
 */
function getFileExtName(path) {
	try {
		let arr = path.split('.')
		return arr[arr.length - 1]
	} catch {
		return ''
	}
}
/**
 * 返回图片扩展名
 * @param {Object} path
 */
function getImageExtName(path) {
	try {
		let arr = path.split('/')
		return arr[arr.length - 1]
	} catch {
		return ''
	}
}
/**
 * 比较时间是否过期
 * @param {Object} d 时间格式
 */
function isEndTime(d) {
  let now = new Date()
  let temp = new Date(d)
  if (parseInt(temp.getTime() / 1000) <= parseInt(now.getTime() / 1000)) {
    return true
  }
  return false
}

function friendlyDate(timestamp) {
	let formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};

	let now = Date.now();
	let seconds = Math.floor((now - timestamp) / 1000);
	let minutes = Math.floor(seconds / 60);
	let hours = Math.floor(minutes / 60);
	let days = Math.floor(hours / 24);
	let months = Math.floor(days / 30);
	let years = Math.floor(months / 12);

	let diffType = '';
	let diffValue = 0;
	if (years > 0) {
		diffType = 'year';
		diffValue = years;
	} else {
		if (months > 0) {
			diffType = 'month';
			diffValue = months;
		} else {
			if (days > 0) {
				diffType = 'day';
				diffValue = days;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}


/**
 * @param {String} src 图片地址
 * @param {Object|Number} size 图片大小 数字为宽高一样， 数组为[宽, 高]
 * @param {String} position 图片位置 local本地，aliyun
 */
function getImage(src, size, position) {
  if (src == '' || src == undefined) return ''
	let h, w;
	if (typeof size === 'number') {
		w = size
		h = size
	} else if (typeof size === 'array') {
		w = size[0]
		h = size[1]
	}
	return src
}

/**
 * @param {String} src 图片地址
 * @param {Object|Number} size 图片大小 数字为宽高一样， 数组为[宽, 高]
 * @param {String} position 图片位置 local本地，aliyun
 */
function getAvatarImage(src, size, position) {
  if (src == '' || src == undefined) return require('@/assets/noavatar.png')
	let h, w;
	if (typeof size === 'number') {
		w = size
		h = size
	} else if (typeof size === 'array') {
		w = size[0]
		h = size[1]
	}
	return src
}

/**
 * @param {String} value 要检查的值
 * @param {Object} type 正则检查类型：cn_mobile手机号
 */
function regExp(value, type) {
	if (value == "" || value == null || value == undefined) {
		return false
	}
	let res = false
	switch (type) {
		case "cn_mobile":
			/**
				数据卡：14号段以前为上网卡专属号段，如中国联通的是145，中国移动的是147,中国电信的是149等等。
				虚拟运营商：170[1700/1701/1702]、162(电信)，1703/1705/1706、165(移动)，1704/1707/1708/1709(联通)、171、167（联通）
				卫星通信： 1740[0-5] (电信)，1349(移动)
				物联网网号：10648、1440 (移动)，10646、146(联通)，10649、1410(电信)
				国家工信部应急通信：1740[6-9]，1741[0-2]
				手机号码: 13[0-9], 14[5,6,7,8,9], 15[0-3, 5-9], 16[2,5,6,7], 17[0-8], 18[0-9], 19[0-3, 5-9]
				移动号段: 13[4-9],147,148,15[0-2,7-9],165,170[3,5,6],172,178,18[2-4,7-8],19[5,7,8]
				联通号段: 130,131,132,145,146,155,156,166,167,170[4,7,8,9],171,175,176,185,186,196
				电信号段: 133,149,153,162,170[0,1,2],173,174[0-5],177,180,181,189,19[0,1,3,9]
				广电号段: 192

				作者：bingxuePI
				链接：https://www.jianshu.com/p/5fbb85967bfd
			*/
			res = /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/.test(value)
			break
		case "number":
			// 数字
			res = /^\d{1,}$/.test(value)
			break
		case "password":
			// 普通密码 只能包含字母、数字和下划线 长度在6~20之间
			res = /\w{6,20}/.test(value)
			break
		case "password_power":
			// 强密码 必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-20之间
			res = /^.*(?=.{8,20})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/.test(value)
			break
		case "url":
			// 链接
			res = /http(s)?:\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?(?:$|[?\/#])/i.test(value)
			break
		default:
			break
	}
	return res
}

/**
 * File对象转换为dataURL、Blob对象转换为dataURL
 * @param {Object} blob File对象或Blob对象
 * @param {Object} callback 回调函数
 */
function readBlobAsDataURL(blob, callback) {
    var a = new FileReader()
    a.onload = function(e) {
      callback(e.target.result)
    }
    a.readAsDataURL(blob)
}

/**
 * img 转为Base64
 * @param {Object} img 图片对象
 */
function convertImgToBase64(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);

    var dataURL = canvas.toDataURL();

    return dataURL;
}

/**
 * Base64 转换为file对象
 * @param {Object} urlData Base64数据
 */
function convertBase64ToFile(urlData) {
    var arr = urlData.split(","),
        type= arr[0].match(/:(.*?);/)[1],
        fileExt = type.split('/')[1],
        bstr = window.atob(arr[1]),
        n = bstr.length,
        ia = new Uint8Array(n);
    while(n--) {
        ia[n] = bstr.charCodeAt(n);
    }
    return new File([ia], "fileName." + fileExt, {type:type});
}

/**
 * Base64 转换为Blob对象
 * @param {Object} urlData Base64数据
 */
function convertBase64ToBlob(urlData) {
    var arr = urlData.split(','),//去掉url的头，并转换为byte
        type = arr[0].match(/:(.*?);/)[1],
        bstr = window.atob(arr[1]),
        n = bstr.length,
        ia = new Uint8Array(n);
    if (!type) {return false;}
    while(n--) {
        ia[n] = bstr.charCodeAt(n);
    }
    var blob;
    try {
        blob = new Blob([ia], {type: type});
    } catch(e) {
        window.BlobBuilder = window.BlobBuilder ||
            window.WebKitBlobBuilder ||
            window.MozBlobBuilder ||
            window.MSBlobBuilder;
        if (e.name === "TypeError" && window.BlobBuilder) {
            var bb = new BlobBuilder();
            bb.append(ia.buffer);
            blob = bb.getBlob("text/plain");
        } else if (e.name === "InvalidStateError") {
            // InvalidStateError (tested on FF13 WinXP)
            blob = new Blob([ia.buffer], {type : type});
        } else {
            blob = false;
        }
    }
    return blob;
}

/**
 * Base64 转换为Blob对象
 * @param {Object} urlData Base64数据
 */
function base64ToBlob(urlData) {
    var arr = urlData.split(','),//去掉url的头，并转换为byte
        type = arr[0].match(/:(.*?);/)[1],
        bstr = window.atob(arr[1]),
        n = bstr.length,
        ia = new Uint8Array(n);
    if (!type) {return false;}
    while(n--) {
        ia[n] = bstr.charCodeAt(n);
    }
    var blob;
    try {
        blob = new Blob([ia], {type: type});
    } catch(e) {
        window.BlobBuilder = window.BlobBuilder ||
            window.WebKitBlobBuilder ||
            window.MozBlobBuilder ||
            window.MSBlobBuilder;
        if (e.name === "TypeError" && window.BlobBuilder) {
            var bb = new BlobBuilder();
            bb.append(ia.buffer);
            blob = bb.getBlob("text/plain");
        } else if (e.name === "InvalidStateError") {
            // InvalidStateError (tested on FF13 WinXP)
            blob = new Blob([ia.buffer], {type : type});
        } else {
            blob = false;
        }
    }
    return blob;
}
/**
 * 图片url转换为Base64
 * @param {Object} url 图片链接
 */
function urlToBase64(url) {
	return new Promise((resolve, reject) => {
		let image = new Image()
		image.onload = function() {
			let canvas = document.createElement('canvas')
			canvas.width = this.naturalWidth;
			canvas.height = this.naturalHeight;
			// 将图片插入画布并开始绘制
			canvas.getContext('2d').drawImage(image, 0, 0)
			// result
			let result = canvas.toDataURL('image/png')
			resolve(result)
		}
		// CORS 策略，会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
		image.setAttribute("crossOrigin", 'Anonymous')
		image.src = url
		// 图片加载失败的错误处理
		image.onerror = () => {
			reject(new Error('图片流异常'));
		}
	})
}

/**
 * 单位分的金额转换为元
 * @param {Object} money
 */
function moneyToYun(money) {
	if (money == '' || isNaN(money) || money == undefined) money = 0
	return  parseInt(money) / 100
}
/**
 * 单位元的金额转换为分
 * @param {Object} money
 */
function yunToMoney(money) {
	if (money == '' || isNaN(money) || money == undefined) money = 0
	return parseInt((money * 100).toFixed(2))
}
/**
 * 单位元的金额转换为元
 * @param {Object} money
 */
function yunToYun(money) {
	if (money == '' || isNaN(money) || money == undefined) money = 0
	return parseInt((money * 100).toFixed(2)) / 100
}

export default {
  getImageExtName,
  getFileExtName,
  friendlyDate,
  parseTime,
  formatTime,
  getImage,
  getAvatarImage,
  regExp,
  convertBase64ToBlob,
  convertBase64ToFile,
  convertImgToBase64,
  readBlobAsDataURL,
  base64ToBlob,
  moneyToYun,
  yunToMoney,
  yunToYun,
  urlToBase64,
  isEndTime
}
